<?php
	class AdministrationController extends Ovis_Controller
	{
		/**
		* The default action - show the home page
		*/
		private $_menuName = 'Administration';

		public function init()
		{
			parent::init();
			$this->checkInstance();
			$userInformation = Ovis_Controller::getLoggedUser();
			$this->view->assign(Sss_Ultility_CommonViewParamater::FULLNAME, $userInformation['fullname']);
		}
		public function loginAction()
		{
			$this->_redirect('/user/login');
		}

		public function indexAction()
		{
			$this->_redirect("/administration/shepherd-instance");
		}

		public function userAction()
		{
			try {
				$userInformation = Ovis_Controller::getLoggedUser();
				if($userInformation['accounttype'] != Sss_Ultility_Setting::ACCOUNT_OVIS){
					$this->_redirect('/user/login');
				}
				$accountTable = new Application_Model_Mapper_Account();
				$systemtypesTable = new Application_Model_Mapper_SystemType();

				$get  = $this->getRequest()->getParams();
				$isSearch = isset($get['s']) && $get['s'] == 1;
				//get order, page, limit param
				$filterParam[Sss_Ultility_CommonViewParamater::ORDERFIELD] = isset($get[Sss_Ultility_CommonViewParamater::ORDERFIELD]) ? $get[Sss_Ultility_CommonViewParamater::ORDERFIELD] : null;
				$filterParam[Sss_Ultility_CommonViewParamater::ORDERTYPE]  = isset($get[Sss_Ultility_CommonViewParamater::ORDERTYPE]) ? $get[Sss_Ultility_CommonViewParamater::ORDERTYPE] : null;
				$filterParam[Sss_Ultility_CommonViewParamater::PAGE] = isset($get[Sss_Ultility_CommonViewParamater::PAGE]) ? $get[Sss_Ultility_CommonViewParamater::PAGE] : 1;

				//param filter: omit title text in field
				$paramUserName    = $isSearch ? strcmp($this->getRequest()->getParam('username', Sss_Ultility_CommonViewParamater::UNDERFINE), Resources::_('USER_NAME')) == 0 ? '' : $this->getRequest()->getParam('username', Sss_Ultility_CommonViewParamater::UNDERFINE) : '';
				$paramFullName    = $isSearch ? strcmp($this->getRequest()->getParam('fullname', Sss_Ultility_CommonViewParamater::UNDERFINE), Resources::_('FULL_NAME')) == 0 ? '' : $this->getRequest()->getParam('fullname', Sss_Ultility_CommonViewParamater::UNDERFINE) : '';
				$paramAccountType = $isSearch ? strcmp($this->getRequest()->getParam('accounttype', Sss_Ultility_CommonViewParamater::UNDERFINE), Resources::_('ACCOUNT_TYPE')) == 0 ? '' : $this->getRequest()->getParam('accounttype', Sss_Ultility_CommonViewParamater::UNDERFINE) : '';


				//get filter
				$filterParam['username']    = $this->getValueRequest(Sss_Ultility_CommonViewParamater::FIX . 'username', trim($paramUserName), Sss_Ultility_SessionName::ACCOUNT_OVIS_SESSION);
				$filterParam['fullname']    = $this->getValueRequest(Sss_Ultility_CommonViewParamater::FIX . 'fullname', trim($paramFullName), Sss_Ultility_SessionName::ACCOUNT_OVIS_SESSION);
				$filterParam['accounttype'] = $this->getValueRequest(Sss_Ultility_CommonViewParamater::FIX . 'accounttype', trim($paramAccountType), Sss_Ultility_SessionName::ACCOUNT_OVIS_SESSION);

				//load account list, accounttype list
				$typeUser = $systemtypesTable->getSystemBySystemName(Sss_Ultility_SystemName::ACCOUNTS);
				$this->view->assign(Sss_Ultility_CommonViewParamater::TYPE, $typeUser);

				// list account
				$list = $accountTable->getListByType($this->view->limit, 0, $filterParam);
				$row  = $list->list;

				$pagination = $list->pagination;
				$this->view->assign(Sss_Ultility_CommonViewParamater::FILTER_PARAM, $filterParam);
				$this->view->assign(Sss_Ultility_CommonViewParamater::ROW, $row);
				$this->view->assign(Sss_Ultility_CommonViewParamater::PAGINATION, $pagination);

				$arrQueryString = Sss_Ultility_AdministrationFunction::getQueyString($isSearch, $filterParam);
				$this->view->assign(Sss_Ultility_CommonViewParamater::QUERY_STRING, $arrQueryString['querystring']);
				$this->view->assign(Sss_Ultility_CommonViewParamater::ORDER_QUERY_STRING, $arrQueryString['oquerystring']);
				//action button
				$actionbuttons = array(
				new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::ADD, 'add-user', Resources::_('ADD_NEW_USER')),
				new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::EXPORT, 'user-export?export=1'),
				new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::PRINTF, 'user-export?print=1'),
				new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::SEARCH, 'javascript:hideShow(this);', Resources::_('SEARCH'))
				);

				$this->view->assign(Sss_Ultility_CommonViewParamater::ACTION_BUTTONS, $actionbuttons);
				//delete user ovis
				$accountId = $this->getRequest()->getParam('accountid', -1);
				if ($userInformation && isset($accountId) && $accountId != -1) {
					$account = $accountTable->getById($accountId);
					$result = Sss_Ultility_AdministrationFunction::deleteUser($account, $accountId,$accountTable);
					$this->redirect($result, $this->view->url(array(
					Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
					Sss_Ultility_CommonViewParamater::ACTION => $this->view->actionName
					)));
				}
				//reset password
				$resetId = $this->getRequest()->getParam(Sss_Ultility_CommonViewParamater::RESET_PASSWORD_ID, -1);
				if (isset($resetId) && $resetId != -1) {
					$result = Sss_Ultility_AdministrationFunction::resetPassword($account, $params, $resetId);
					$this->redirect($result, $this->view->url(array(
					Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
					Sss_Ultility_CommonViewParamater::ACTION => $this->view->actionName
					)));
				}

				//get breadscrumb
				$breadscrumbs = array(
				new Sss_CommonEntity_BreadScrumb($this->_menuName, ''),
				new Sss_CommonEntity_BreadScrumb(Resources::_('USER'), '#')
				);
				$this->view->assign(Sss_Ultility_CommonViewParamater::BREADSCRUMBS, $breadscrumbs);
			} catch (Exception $e) { 
				Sss_Ultility_Common::logger()->log($e, Zend_Log::ERR);
				$this->redirect($e->getMessage(),$this->view->url(array(
				Sss_Ultility_CommonViewParamater::CONTROLLER => 'error',
				Sss_Ultility_CommonViewParamater::ACTION => 'error'
				)));
			}
		}
		public function addUserAction()
		{
			try {
				$userInformation = Ovis_Controller::getLoggedUser();
				if($userInformation['accounttype'] != Sss_Ultility_Setting::ACCOUNT_OVIS) {
					$this->_redirect('/user/login');
				}
				$accountTable = new Application_Model_Mapper_Account();
				$accountContructor = new Application_Model_Account();
				$systemtypesTable = new Application_Model_Mapper_SystemType();
				//load accounttype
				$typeUser = $systemtypesTable->getSystemBySystemName(Sss_Ultility_SystemName::ACCOUNTS);
				$this->view->assign(Sss_Ultility_CommonViewParamater::TYPE, $typeUser);
				$params = $this->_request->getParams();
				//insert user 
				if ($userInformation && isset($params[Sss_Ultility_CommonViewParamater::BTN_SAVE])) {
					$otrs = new Sss_Ultility_OtrsServices();
					$passWordDefault   = Sss_Ultility_Common::genRandomString();
					$isActived = isset($params['isactivated']) ? 1 : 0;
					$fullName       =  addslashes($params['fullname']);
					$userName       =  addslashes($params['username']);
					$email          =  addslashes($params['email']);
					$type           = $params['accounttype'];
					$encryptedPassword = Sss_Crypt::factory()->encrypt($passWordDefault);
					$accountContructor->setUsername($userName);
					$accountContructor->setFullname($fullName);
					$accountContructor->setPassword($encryptedPassword);
					$accountContructor->setEmail($email);
					$accountContructor->setAccountType($type);
					$accountContructor->setIsActivated($isActived);
					$accountContructor->setIsBlocked(0);
					$accountContructor->setSalt('');
					$accountContructor->setIsSystem(0);
					$accountContructor->setOtrsUserId(0);
					$accountContructor->setIsarchived(0);
					//Process adding new user  
					$list = $accountTable->getUserList();
					$result = Sss_Ultility_AdministrationFunction::checkUserExist($list, $params);
					if ($result != null) {
						$this->redirect($result, $this->view->url(array(
						Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
						Sss_Ultility_CommonViewParamater::ACTION => $this->view->actionName
						)));
					}
					//Process adding new user  
					$accountId = $accountTable->save($accountContructor);
					
					if (isset($accountId)) {
						// Get service OTRS and create new user OTRS relation with user ovis account
						if($type == Sss_Ultility_Setting::ACCOUNT_VENDOR) {
							$user_otrs_id = 0;
						} else {
							$arrParams = array();
							$arrParams['fullname'] =  $fullName;
							$arrParams['username'] =  $userName . $accountId;
							$arrParams['password'] =  $encryptedPassword;
							$arrParams['role'] =  0;
							$arrParams['email'] =  $accountId.$email;
							$arrParams['wsuser'] =  USER_SERVICE;
							$arrParams['wspass'] =  PASSWORD_SERVICE;
							$user_otrs_id   = $otrs->createUser(USER_SERVICE_ID, 1, $arrParams);
							if(is_null($user_otrs_id)) {
								$this->redirect(Resources::_('USER_NAME_EXIST'), $this->view->url(array(
								Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
								Sss_Ultility_CommonViewParamater::ACTION => $this->view->actionName
								)));
							}
						}
						$result = Sss_Ultility_AdministrationFunction::processOTRSAccount($params, $accountId, $user_otrs_id, $type, $passWordDefault, $otrs);
						Sss_Ultility_Common::sendMail(EMAIL_SYSTEM, $email, $subject, $body);
						$this->redirect($result, $this->view->url(array(
						Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
						Sss_Ultility_CommonViewParamater::ACTION => 'user'
						)));
					} else {
						$this->redirect(Resources::_('ADD_USER_FAIL'), $this->view->url(array(
						Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
						Sss_Ultility_CommonViewParamater::ACTION => 'user'
						)));
					}
				}
				//get breadscrumb
				$breadscrumbs = array(
				new Sss_CommonEntity_BreadScrumb($this->_menuName, ''),
				new Sss_CommonEntity_BreadScrumb(Resources::_('USER'), '#'),
				new Sss_CommonEntity_BreadScrumb(Resources::_('ADD_NEW_USER'), '#')
				);
				$this->view->assign(Sss_Ultility_CommonViewParamater::BREADSCRUMBS, $breadscrumbs);
			} catch (Exception $e) {
				Sss_Ultility_Common::logger()->log($e, Zend_Log::ERR);
				$this->redirect($e->getMessage(),$this->view->url(array(
				Sss_Ultility_CommonViewParamater::CONTROLLER => 'error',
				Sss_Ultility_CommonViewParamater::ACTION => 'error'
				)));
			}
		}
		public function editUserAction()
		{
			$userInformation = Ovis_Controller::getLoggedUser();
			if($userInformation['accounttype'] != Sss_Ultility_Setting::ACCOUNT_OVIS) {
				$this->_redirect('/user/login');
			}
			$accountTable = new Application_Model_Mapper_Account();
			$systemtypesTable = new Application_Model_Mapper_SystemType();
			$vendorAccountTable = new Application_Model_Mapper_VendorAccount();
			$vendorAccountContructor = new Application_Model_VendorAccount();

			//load dropdown list accounttype
			$typeUser = $systemtypesTable->getSystemBySystemName(Sss_Ultility_SystemName::ACCOUNTS);
			$this->view->assign(Sss_Ultility_CommonViewParamater::TYPE, $typeUser);
			$params = $this->_request->getParams();
			$accountId = $this->getRequest()->getParam('accountid', -1);
			if (((int) $accountId == -1 || (int) $accountId == 0) && isset($params['accountid']))
				$accountId = $params['accountid'];
			$this->view->assign('accountid', $accountId);
			//get account
			$accountType = $accountTable->getAccountTypeByAccountId($accountId);
			if($accountType->accounttype == Sss_Ultility_Setting::ACCOUNT_VENDOR) {
				$account = $accountTable->getById($accountId,Sss_Ultility_Setting::ACCOUNT_VENDOR);
			} else {
				$account = $accountTable->getById($accountId);
			}
			$this->view->assign(Sss_Ultility_CommonViewParamater::ACCOUNT, $account);

			//edit user
			if ($userInformation && isset($params[Sss_Ultility_CommonViewParamater::BTN_SAVE])) {
				$isActivated = isset($params['isactivated']) ? 1 : 0;
				$accountUpdate = $accountTable->findById($accountId);
				$accountUpdate->setUsername(addslashes($params['username']));
				$accountUpdate->setFullname(addslashes($params['fullname']));
				$accountUpdate->setEmail(addslashes($params['email']));
				$accountUpdate->setAccountType($params['accounttype']);
				$accountUpdate->setIsActivated($isActivated);
				//Process adding new user  
				$queryString = '?' . 'accountid' . '=' . $accountId;
				$list        = $accountTable->getUserList($accountId);
				foreach ($list as $l) {
					if (trim($l['username']) == trim($params['username'])) {
						$this->redirect(Resources::_('USER_NAME_EXIST'), $this->view->url(array(
						Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
						Sss_Ultility_CommonViewParamater::ACTION => $this->view->actionName
						)) . $queryString);
					}
					if (trim($l['email']) == trim($params['email'])) {
						$this->redirect(Resources::_('EMAIL_EXIST'), $this->view->url(array(
						Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
						Sss_Ultility_CommonViewParamater::ACTION => $this->view->actionName
						)) . $queryString);
					}
				}
				//Process edit user  
				$Id = $accountTable->save($accountUpdate);
				if (isset($Id)) {
					if($accountType->accounttype == Sss_Ultility_Setting::ACCOUNT_VENDOR) {
						//Process delete vendor account
						$arrVendorAccountId = array(
							'account = ?' => $accountId
						);
						$vendorAccountTable->deleteRow(null, $arrVendorAccountId);
					}
					//Process insert data to vendor account
					if(!empty($params['vendorid'])) {
						$vendorAccountContructor->setAccount($accountId);
						$vendorAccountContructor->setVendor($params['vendorid']);
						$vendorAccountTable->save($vendorAccountContructor);
					}
					
					$message = Resources::_('EDIT_USER_SUCCESSFULL');
				} else {
					$message = Resources::_('EDIT_USER_FAIL');
				}
				$this->redirect($message, $this->view->url(array(
						Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
						Sss_Ultility_CommonViewParamater::ACTION => 'user'
				)));
			}

			//get breadscrumb
			$breadscrumbs = array(
			new Sss_CommonEntity_BreadScrumb($this->_menuName, ''),
			new Sss_CommonEntity_BreadScrumb(Resources::_('USER'), '#'),
			new Sss_CommonEntity_BreadScrumb(Resources::_('EDIT_USER'), '#')
			);
			$this->view->assign(Sss_Ultility_CommonViewParamater::BREADSCRUMBS, $breadscrumbs);
		}

		public function userExportAction()
		{
			$userInformation = Ovis_Controller::getLoggedUser();
			if($userInformation['accounttype'] != Sss_Ultility_Setting::ACCOUNT_OVIS) {
				$this->_redirect('/user/login');
			}
			$accountTable = new Application_Model_Mapper_Account();

			//get order, page, limit param
			$filterParam[Sss_Ultility_CommonViewParamater::ORDERFIELD] = isset($get[Sss_Ultility_CommonViewParamater::ORDERFIELD]) ? $get[Sss_Ultility_CommonViewParamater::ORDERFIELD] : null;
			$filterParam[Sss_Ultility_CommonViewParamater::ORDERTYPE]  = isset($get[Sss_Ultility_CommonViewParamater::ORDERTYPE]) ? $get[Sss_Ultility_CommonViewParamater::ORDERTYPE] : null;
			$filterParam[Sss_Ultility_CommonViewParamater::PAGE] = isset($get[Sss_Ultility_CommonViewParamater::PAGE]) ? $get[Sss_Ultility_CommonViewParamater::PAGE] : 1;

			//param filter: omit title text in field
			$paramUserName     = strcmp($this->getRequest()->getParam('username', Sss_Ultility_CommonViewParamater::UNDERFINE), Resources::_('USER_NAME')) == 0 ? '' : $this->getRequest()->getParam('username', Sss_Ultility_CommonViewParamater::UNDERFINE);
			$paramFullName     = strcmp($this->getRequest()->getParam('fullname', Sss_Ultility_CommonViewParamater::UNDERFINE), Resources::_('FULL_NAME')) == 0 ? '' : $this->getRequest()->getParam('fullname', Sss_Ultility_CommonViewParamater::UNDERFINE);





			//get filter
			$filterParam['username']     = $this->getValueRequest(Sss_Ultility_CommonViewParamater::FIX . 'username', trim($paramUserName), Sss_Ultility_SessionName::ACCOUNT_OVIS_SESSION);
			$filterParam['fullname']     = $this->getValueRequest(Sss_Ultility_CommonViewParamater::FIX . 'fullname', trim($paramFullName), Sss_Ultility_SessionName::ACCOUNT_OVIS_SESSION);
			$filterParam['accounttype']  = $this->getValueRequest(Sss_Ultility_CommonViewParamater::FIX . 'accounttype', trim($paramFullName), Sss_Ultility_SessionName::ACCOUNT_OVIS_SESSION);
			$filterParam['lastest_login'] = $this->getValueRequest(Sss_Ultility_CommonViewParamater::FIX . 'lastest_login', trim($paramFullName), Sss_Ultility_SessionName::ACCOUNT_OVIS_SESSION);
			$filterParam['isactivated']     = $this->getValueRequest(Sss_Ultility_CommonViewParamater::FIX . 'isactivated', trim($paramFullName), Sss_Ultility_SessionName::ACCOUNT_OVIS_SESSION);

			$list       = $accountTable->getListByType(-1, 0, $filterParam);
			$rowAll     = $list->list;
			$pagination = $list->pagination;
			$this->view->assign(Sss_Ultility_CommonViewParamater::ROW, $rowAll);
			$this->view->assign(Sss_Ultility_CommonViewParamater::PAGINATION, $pagination);
			$count = ((($pagination->pagecurrent * Sss_Ultility_Setting::PAGE_SIZE) - Sss_Ultility_Setting::PAGE_SIZE));
			$columnNames = array(
			Resources::_('ID'),
			Resources::_('USER_NAME'),
			Resources::_('FULL_NAME'),
			Resources::_('ACCOUNT_TYPE'),
			Resources::_('ACTIVATED'),
			Resources::_('LASTEST_LOGIN') 
			);

			$arrData = array();
			$index = 0;
			foreach((array)$rowAll as $row) {
				$count++;
				$arrData[$index][] = $count;
				$arrData[$index][] = $row['username'];
				$arrData[$index][] = $row['fullname'];
				$arrData[$index][] = $row['typename'];
				$arrData[$index][] = $row['isactivated'] ? Resources::_('ACTIVATED') : Resources::_('IN_ACTIVATED');
				$arrData[$index][] = $row['lastest_login'];
				$index++;
			}
			if(isset($_GET['export']))
				$this->exportDataToExcel($columnNames, $arrData, Resources::_('USERS'));
		}
		public function shepherdInstanceAction()
		{
			$instanceTable = new Application_Model_Mapper_Instance();
			$stockLocationTable = new Application_Model_Mapper_StockLocation();
			$stockLocationInstanceTable = new Application_Model_Mapper_StockLocationInstance();
			$get  = $this->getRequest()->getParams();
			$isSearch = isset($get['s']) && $get['s'] == 1;
			
			//get order, page, limit param
			$filterParam[Sss_Ultility_CommonViewParamater::ORDERFIELD] = isset($get[Sss_Ultility_CommonViewParamater::ORDERFIELD]) ? $get[Sss_Ultility_CommonViewParamater::ORDERFIELD] : null;
			$filterParam[Sss_Ultility_CommonViewParamater::ORDERTYPE]  = isset($get[Sss_Ultility_CommonViewParamater::ORDERTYPE]) ? $get[Sss_Ultility_CommonViewParamater::ORDERTYPE] : null;
			$filterParam[Sss_Ultility_CommonViewParamater::PAGE] = isset($get[Sss_Ultility_CommonViewParamater::PAGE]) ? $get[Sss_Ultility_CommonViewParamater::PAGE] : 1;
			
			//param filter: omit title text in field
			$paramName = $isSearch ? strcmp($this->getRequest()->getParam('instancename', Sss_Ultility_CommonViewParamater::UNDERFINE), Resources::_('NAME')) == 0 ? '' : $this->getRequest()->getParam('instancename', Sss_Ultility_CommonViewParamater::UNDERFINE) : '';
			$paramHandleName = $isSearch ? strcmp($this->getRequest()->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE), Resources::_('HANDLE')) == 0 ? '' : $this->getRequest()->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE) : '';
			$paramFullName = $isSearch ? strcmp($this->getRequest()->getParam('fullname', Sss_Ultility_CommonViewParamater::UNDERFINE), Resources::_('CUSTOMER')) == 0 ? '' : $this->getRequest()->getParam('fullname', Sss_Ultility_CommonViewParamater::UNDERFINE) : '';
			
			//get filter
			$filterParam['instancename'] = $this->getValueRequest('instancename', trim($paramName), Sss_Ultility_SessionName::INSTANCE_SESSION);
			$filterParam['handle']        = $this->getValueRequest('handle', trim($paramHandleName), Sss_Ultility_SessionName::INSTANCE_SESSION);
			$filterParam['fullname']      = $this->getValueRequest('fullname', trim($paramFullName), Sss_Ultility_SessionName::INSTANCE_SESSION);
			$userInformation = Ovis_Controller::getLoggedUser();
			if ($userInformation && $userInformation['accounttype'] == Sss_Ultility_Setting::ACCOUNT_OVIS) {
				//delete instance
				$instanceId = $this->getRequest()->getParam('instanceid', -1);
				if (isset($instanceId) && $instanceId != -1) {
					$instance = $instanceTable->getById($instanceId);
					$getStockLocationByInstance = $stockLocationInstanceTable->getStockLocationByInstance();
					foreach($getStockLocationByInstance as $s) {
						$stockLocationUpdate = $stockLocationTable->findById($s['stocklocation']);
						$stockLocationUpdate->setShepherd(0);
						$stockLocationId = $stockLocationTable->save($stockLocationUpdate);  
						$arrStockLocationId = array(
						'instance = ?' => $instanceId,
						'stocklocation = ?' => $s['stocklocation']
						);
						$stockLocationId = $stockLocationInstanceTable->deleteRow(null,$arrStockLocationId); 
					}
					if ($instance->logo && file_exists(getcwd() . $instance->logo))
						unlink(getcwd() . $instance->logo);
					$deleteId = $instanceTable->deleteRow(( int ) $instanceId);
					$newDBName = SHEPHERD_SUFIX . Sss_Ultility_Common::formatString($instanceId, Sss_Ultility_Setting::FORMAT_NUMBER);
					Sss_Ultility_Common::dropDatabase($newDBName);
					if (isset($deleteId)) {
						$this->redirect(Resources::_('DELETE_INSTANCE_SUCCESSFULL'), $this->view->url(array(
						Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
						Sss_Ultility_CommonViewParamater::ACTION => 'shepherd-instance'
						)));
					} else {
						$this->redirect(Resources::_('DELETE_INSTANCE_FAIL'), $this->view->url(array(
						Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
						Sss_Ultility_CommonViewParamater::ACTION => 'shepherd-instance'
						)));
					}
				}
			}

			//get list instance
			$list       = $instanceTable->getInstanceList($this->view->limit, 0, $filterParam);
			$row        = $list->list;

			$result = Sss_Ultility_AdministrationFunction::processCompanyOwner($row);
			$this->view->assign(Sss_Ultility_CommonViewParamater::ACCOUNT, $result['listcompnayowner']);
			$this->view->assign('companyowner', $result['listcompnayownerid']);
			$pagination = $list->pagination;
			$this->view->assign(Sss_Ultility_CommonViewParamater::FILTER_PARAM, $filterParam);
			$this->view->assign(Sss_Ultility_CommonViewParamater::ROW, $row);
			$this->view->assign(Sss_Ultility_CommonViewParamater::PAGINATION, $pagination);

			$arrQueryString = Sss_Ultility_AdministrationFunction::getQueyString($isSearch, $filterParam);
			$this->view->assign(Sss_Ultility_CommonViewParamater::QUERY_STRING, $arrQueryString['querystring']);
			$this->view->assign(Sss_Ultility_CommonViewParamater::ORDER_QUERY_STRING, $arrQueryString['oquerystring']);

			//action button
			if($userInformation['accounttype'] == Sss_Ultility_Setting::ACCOUNT_OVIS) {
				$actionbuttons = array(
				new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::ADD, 'add-shepherd-instance', Resources::_('ADD_NEW_INSTANCE')),
				new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::SEARCH, 'javascript:hideShow(this);', Resources::_('SEARCH'))
				);
			} else {
				$actionbuttons = array(
				new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::SEARCH, 'javascript:hideShow(this);', Resources::_('SEARCH'))
				);
			}
			$this->view->assign(Sss_Ultility_CommonViewParamater::ACTION_BUTTONS, $actionbuttons);

			//get breadscrumb
			$breadscrumbs = array(
			new Sss_CommonEntity_BreadScrumb($this->_menuName, ''),
			new Sss_CommonEntity_BreadScrumb(Resources::_('MY_SHEPHERD'), '#')
			);
			$this->view->assign(Sss_Ultility_CommonViewParamater::BREADSCRUMBS, $breadscrumbs);
		}

		public function addShepherdInstanceAction()
		{
			$userInformation = Ovis_Controller::getLoggedUser();
			if($userInformation['accounttype'] != Sss_Ultility_Setting::ACCOUNT_OVIS){
				$this->_redirect('/user/login');
			}
			$instanceTable = new Application_Model_Mapper_Instance();
			$stockLocationTable = new Application_Model_Mapper_StockLocation();

			$list = $instanceTable->getList();
			$this->view->assign(Sss_Ultility_CommonViewParamater::ROW, $list);

			//get stock locations
			$stockLocations = $stockLocationTable->getStockLocationForInstance();
			$this->view->assign(Sss_Ultility_CommonViewParamater::STOCKLOCATIONS, $stockLocations);

			$params = $this->_request->getParams();
			//insert instance
			if (isset($params[Sss_Ultility_CommonViewParamater::BTN_SAVE])) {
				$userInformation = Ovis_Controller::getLoggedUser();
				$isExist = false;
				$handleInstance = addslashes($params['handle']);
				if ($userInformation) {
					foreach ($list as $l) {
						if (trim($l['handle']) == trim($params['handle'])) {
							$isExist = true;
						}
					}
					if($isExist){
						$this->view->assign(Sss_Ultility_CommonViewParamater::MSG, Resources::_('HANDLE_NAME_EXIST'));
						return; 
					}
					try{
						$id = Sss_Ultility_AdministrationFunction::addInstance($instanceTable,$params);
					}catch(Exception $e){
						$this->redirect(Resources::_('ADD_INSTANCE_FAIL'), $this->view->url(array(
						Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
						Sss_Ultility_CommonViewParamater::ACTION => 'shepherd-instance'
						)));
					}
					if (isset($id)) {
						//add stock location to instance
						$arrStockLocationId = explode('_', $params['stocklocation']);
						$message = Sss_Ultility_AdministrationFunction::addStockLocationToInstance($id,$arrStockLocationId,$handleInstance,$params);
					} else {
						$message = Resources::_('ADD_INSTANCE_FAIL');
					}
					$this->redirect($message, $this->view->url(array(
							Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
							Sss_Ultility_CommonViewParamater::ACTION => 'shepherd-instance'
					)));
				}
			}

			//get breadscrumb
			$breadscrumbs = array(
			new Sss_CommonEntity_BreadScrumb($this->_menuName, ''),
			new Sss_CommonEntity_BreadScrumb(Resources::_('MY_SHEPHERD'), '#'),
			new Sss_CommonEntity_BreadScrumb(Resources::_('ADD_NEW_INSTANCE'), '#')
			);
			$this->view->assign(Sss_Ultility_CommonViewParamater::BREADSCRUMBS, $breadscrumbs);
		}
		public function editShepherdInstanceAction()
		{
			$userInformation = Ovis_Controller::getLoggedUser();
			if($userInformation['accounttype'] != Sss_Ultility_Setting::ACCOUNT_OVIS){
				$this->_redirect('/user/login');
				return;
			}
			$stockLocationTable = new Application_Model_Mapper_StockLocation();
			$instanceTable = new Application_Model_Mapper_Instance();
			$stockLocationInstanceTable = new Application_Model_Mapper_StockLocationInstance();

			//get instance id
			$instanceId = $this->getRequest()->getParam('instanceid', -1);
			if (($instanceId == -1 || ( int ) $instanceId == 0) && isset($params['instanceid']))
				$instanceId = $params['instanceid'];
			$this->view->assign('instanceid', $instanceId);

			//get stock locations
			$stockLocations = $stockLocationTable->getStockLocationForInstance($instanceId);
			$this->view->assign(Sss_Ultility_CommonViewParamater::STOCKLOCATIONS, $stockLocations);

			$params = $this->_request->getParams();

			//get instance by id
			$instance = $instanceTable->getById($instanceId);
			$this->view->assign(Sss_Ultility_CommonViewParamater::INSTANCE, $instance);

			//get stock location id
			$stockLocation = $this->getRequest()->getParam('stocklocation', -1);
			if ($stockLocation == -1 || ( int ) $stockLocation == 0)
				$stockLocation = $instance->stocklocation;
			$this->view->assign('stocklocation', $stockLocation);

			//get company owner account name by stock location
			$stockLocationByInstance           = $stockLocationTable->getLocationByInstance($instanceId);
			$stockLocationName = '';
			$stockLocationIds = '';
			foreach($stockLocationByInstance as $c){
				if($stockLocationName != ''){
					$stockLocationName = $stockLocationName.', ';
				}
				if($stockLocationIds != ''){
					$stockLocationIds = $stockLocationIds.'_';
				}
				$stockLocationIds = $stockLocationIds.$c['stocklocation'];
				$stockLocationName = $stockLocationName.$c['stocklocationname'];
			}
			$this->view->assign(Sss_Ultility_CommonViewParamater::ACCOUNT, $stockLocationName);
			$this->view->assign(Sss_Ultility_CommonViewParamater::STOCK_LOCATION_IDS, $stockLocationIds);

			if($userInformation['accounttype'] != Sss_Ultility_Setting::ACCOUNT_OVIS){
				if($stockLocationArray->companyowner != $userInformation['accountid']){
					$this->_redirect('/user/login');
					return;
				}
			}

			//edit instance
			if (isset($params[Sss_Ultility_CommonViewParamater::BTN_SAVE])) {
				$userInformation = Ovis_Controller::getLoggedUser();
				if ($userInformation) {
					$arrStockLocationId = explode('_', $params['stocklocation']);
					$id = Sss_Ultility_AdministrationFunction::editInstance($userInformation,$instanceTable,$stockLocationTable,$stockLocationInstanceTable,$params,$instanceId,$stockLocation,$arrStockLocationId);
					if (isset($id)) {
						//add stock location to instance
						if (false != $arrStockLocationId) {
							for ($i = 0; $i < count($arrStockLocationId); $i++) {
								$stockLocationId = $arrStockLocationId[$i];
								if ($stockLocationId > 0 && $stockLocationId != '') {
									$stockInstanceContructor = new Application_Model_StockLocationInstance();
									$stockInstanceContructor->setStockLocation($stockLocationId);
									$stockInstanceContructor->setInstance($instanceId);
									$stockLocationInstanceTable->save($stockInstanceContructor);
								}
							}
						}

						$this->redirect(Resources::_('EDIT_INSTANCE_SUCCESSFULL'), $this->view->url(array(
						Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
						Sss_Ultility_CommonViewParamater::ACTION => 'shepherd-instance'
						)));
					} else {
						$this->redirect(Resources::_('EDIT_INSTANCE_FAIL'), $this->view->url(array(
						Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
						Sss_Ultility_CommonViewParamater::ACTION => 'shepherd-instance'
						)));
					}
				}
			}
			//get breadscrumb
			$breadscrumbs = array(
			new Sss_CommonEntity_BreadScrumb($this->_menuName, ''),
			new Sss_CommonEntity_BreadScrumb(Resources::_('MY_SHEPHERD'), 'shepherd-instance'),
			new Sss_CommonEntity_BreadScrumb(Resources::_('EDIT_INSTANCE'), '#')
			);
			$this->view->assign(Sss_Ultility_CommonViewParamater::BREADSCRUMBS, $breadscrumbs);
		}

		public function shepherdInstanceDetailAction()
		{
			try {
				$userInformation = Ovis_Controller::getLoggedUser();
				$stockLocationTable = new Application_Model_Mapper_StockLocation();
				$instanceTable = new Application_Model_Mapper_Instance();
				$accountOvisTable = new Application_Model_Mapper_Account();
				$accountTable = new Shepherd_Model_Mapper_Account();
	
				$params = $this->_request->getParams();
				$instanceId = $this->getRequest()->getParam('instanceid', -1);
				if (($instanceId == -1 || ( int ) $instanceId == 0) && isset($params['instanceid'])) {
					$instanceId = $params['instanceid'];
				}
				if ($instanceId > 0) 
					$accountTable->checkEsixtedColumns('otrs_user_id', $instanceId);
				$this->view->assign('instanceid', $instanceId);
				$instance = $instanceTable->getById($instanceId);
				$handle = $instance->handle;
				$this->view->assign(Sss_Ultility_CommonViewParamater::INSTANCE, $instance);
				//get stocklocation list
				$stockLocationList = Sss_Ultility_AdministrationFunction::setStocklocationList($stockLocationTable,$instance,$instanceId);
				$this->view->assign('stocklocationname', $stockLocationList);
	
				//get company owner account name by stock location
				$compnayOwner           = $accountOvisTable->getCompanyOwnerByStockLocation($instance->stocklocation);
				$arrCompanyOwner = array();
				foreach($compnayOwner as $c){
					$arrCompanyOwner[] = $c['companyowner'];
				}
				if($userInformation['accounttype'] != Sss_Ultility_Setting::ACCOUNT_OVIS){
					if(!in_array($userInformation['accountid'], $arrCompanyOwner)){
						$this->_redirect('/user/login');
					}
				}
				//check login
				$accountId = $this->getRequest()->getParam(Sss_Ultility_CommonViewParamater::LOGIN_SHEPHERD_INSTANCE, -1);
				if (isset($accountId) && $accountId != -1 && $userInformation) {
					try {
						$account = $instanceTable->getAccountByInstance($instanceId, $accountId);
						if($account != false) {
							if($account->isactivated == 1) {
								$sessionStartLogin = new Zend_Session_Namespace(Sss_Ultility_SessionName::START_LOGIN_SESSION . $handle);
								$sessionStartLogin->startLogin  = Sss_Ultility_Setting::END_LOGIN;
								//Authentication with POST params
								$result = Sss_Controller_Shepherd_UserAdapter::checkLogin(array(
								'username' => $account->username,
								'password' => $account->password,
								Sss_Ultility_CommonViewParamater::LOGIN_SHEPHERD_INSTANCE => $instanceId
								), $instanceId, $handle);
								if ($result) {
									Sss_Ultility_AdministrationFunction::checkLoginShepherdDetail($handle,$instance,$instanceId,$account,$accountOvisTable,$instanceTable,$accountTable);
								} else {
									$this->redirect(Resources::_('ACCOUNT_LOGIN_FAIL'), $this->view->url(array(
									Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
									Sss_Ultility_CommonViewParamater::ACTION => 'shepherd-instance-detail'
									)).'?instanceid='.$instanceId);
								}
							}
						}
					} catch(Exception $e){
						Sss_Ultility_Common::logger()->log($e, Zend_Log::ERR);
					}
				}
				//reset password
				$resetId = $this->getRequest()->getParam(Sss_Ultility_CommonViewParamater::RESET_PASSWORD_ID, -1);
				if (isset($resetId) && $resetId != -1) {
					$message = Sss_Ultility_AdministrationFunction::checkResetShepherdDetail($instanceTable,$instanceId,$resetId,$instance);
					$this->redirect($message, $this->view->url(array(
							Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
							Sss_Ultility_CommonViewParamater::ACTION => $this->view->actionName
					)).'?'.'instanceid'.'='.$instanceId);
				}
				//get list user of shepherd
				try {
					//get order, page, limit param
					$filterParam[Sss_Ultility_CommonViewParamater::ORDERFIELD] = isset($params[Sss_Ultility_CommonViewParamater::ORDERFIELD]) ? $params[Sss_Ultility_CommonViewParamater::ORDERFIELD] : null;
					$filterParam[Sss_Ultility_CommonViewParamater::ORDERTYPE]  = isset($params[Sss_Ultility_CommonViewParamater::ORDERTYPE]) ? $params[Sss_Ultility_CommonViewParamater::ORDERTYPE] : null;                
					$filterParam[Sss_Ultility_CommonViewParamater::PAGE] = isset($params[Sss_Ultility_CommonViewParamater::PAGE]) ? $params[Sss_Ultility_CommonViewParamater::PAGE] : 1;
					//get filter
					$filterParam['username'] = $this->getValueRequest('username', '', Sss_Ultility_SessionName::INSTANCE_DETAIL_SESSION);
					$filterParam['fullname'] = $this->getValueRequest('fullname', '', Sss_Ultility_SessionName::INSTANCE_DETAIL_SESSION);
					$filterParam['rolename'] = $this->getValueRequest('rolename', '', Sss_Ultility_SessionName::INSTANCE_DETAIL_SESSION);
					$filterParam['isactivated'] = 1;
					$list       =  $instanceTable->getAccountsByInstance($instanceId, $this->view->limit, 0, $filterParam); 
					$row        = $list->list;
					$pagination = $list->pagination;
					$this->view->assign(Sss_Ultility_CommonViewParamater::ROW, $row);
					$this->view->assign(Sss_Ultility_CommonViewParamater::PAGINATION, $pagination);
					// Auto login when login to shepherd
					Sss_Ultility_AdministrationFunction::autoLoginWhenLoginShepherd($row,$instance);
				} catch (Exception $e) {
					Sss_Ultility_Common::logger()->log($e, Zend_Log::ERR);
				}
				//get breadscrumb
				$breadscrumbs = Sss_Ultility_AdministrationFunction::breadscrumbShepherdDetail($this->_menuName);
				$this->view->assign(Sss_Ultility_CommonViewParamater::BREADSCRUMBS, $breadscrumbs);
			} catch (Exception $e) {
				Sss_Ultility_Common::logger()->log($e, Zend_Log::ERR);
			}
		}

		public function vendorInformationAction()
		{
			$vendorTable = new Application_Model_Mapper_Vendor();
			$get = $this->_request->getParams();
			//get order, page, limit param
			$filterParam[Sss_Ultility_CommonViewParamater::ORDERFIELD] = isset($get[Sss_Ultility_CommonViewParamater::ORDERFIELD]) ? $get[Sss_Ultility_CommonViewParamater::ORDERFIELD] : null;
			$filterParam[Sss_Ultility_CommonViewParamater::ORDERTYPE]  = isset($get[Sss_Ultility_CommonViewParamater::ORDERTYPE]) ? $get[Sss_Ultility_CommonViewParamater::ORDERTYPE] : null;
			$filterParam[Sss_Ultility_CommonViewParamater::PAGE] = isset($get[Sss_Ultility_CommonViewParamater::PAGE]) ? $get[Sss_Ultility_CommonViewParamater::PAGE] : 1;
			//test param filter: omit title text in field
			$paramName = $this->getRequest()->getParam('vendorname', Sss_Ultility_CommonViewParamater::UNDERFINE);

			$filterParam['vendorname'] = '';
			if ($paramName != Resources::_('NAME'))
				$filterParam['vendorname'] = $this->getValueRequest('vendorname', $paramName, Sss_Ultility_SessionName::VENDOR_INFORMATION_SESSION);
			//get company list
			$list       = $vendorTable->getVendorList($this->view->limit, 0, $filterParam);
			$row        = $list->list;
			$pagination = $list->pagination;
			$this->view->assign(Sss_Ultility_CommonViewParamater::FILTER_PARAM, $filterParam);
			$this->view->assign(Sss_Ultility_CommonViewParamater::ROW, $row);
			$this->view->assign(Sss_Ultility_CommonViewParamater::PAGINATION, $pagination);
		}

		public function stockLocationInstanceAction()
		{
			$stockLocationTable = new Application_Model_Mapper_StockLocation();
			$get  = $this->getRequest()->getParams(); 
			//get order, page, limit param
			$filterParam[Sss_Ultility_CommonViewParamater::ORDERFIELD] = $this->getValueRequest(Sss_Ultility_CommonViewParamater::ORDERFIELD, $this->getRequest()->getParam(Sss_Ultility_CommonViewParamater::ORDERFIELD, Sss_Ultility_CommonViewParamater::UNDERFINE), Sss_Ultility_SessionName::STOCKLOCATION_COMPANY_OWNER_SEARCH_SESSION);
			$filterParam[Sss_Ultility_CommonViewParamater::ORDERTYPE]  = $this->getValueRequest(Sss_Ultility_CommonViewParamater::ORDERTYPE, $this->getRequest()->getParam(Sss_Ultility_CommonViewParamater::ORDERTYPE, Sss_Ultility_CommonViewParamater::UNDERFINE), Sss_Ultility_SessionName::STOCKLOCATION_COMPANY_OWNER_SEARCH_SESSION);
			$filterParam[Sss_Ultility_CommonViewParamater::PAGE] = isset($get[Sss_Ultility_CommonViewParamater::PAGE]) ? $get[Sss_Ultility_CommonViewParamater::PAGE] : 1; 
			$isSearch = isset($get['s']) && $get['s'] == 1;

			//test param filter: omit title text in field
			$paramName = $isSearch ? strcmp($this->getRequest()->getParam('stocklocationname', Sss_Ultility_CommonViewParamater::UNDERFINE), Resources::_('STOCK_LOCATION_NAME')) == 0 ? '' : $this->getRequest()->getParam('stocklocationname', Sss_Ultility_CommonViewParamater::UNDERFINE) : '';

			$filterParam['stocklocationname'] = '';
			if ($paramName != Resources::_('STOCK_LOCATION_NAME')){
				$filterParam['stocklocationname'] = $this->getValueRequest('fullname', $paramName, Sss_Ultility_SessionName::STOCKLOCATION_INSTANCE_SESSION);
			}
			$instanceId  = $this->getRequest()->getParam('instanceid', -1);
			$this->view->assign('instanceid', $instanceId);
			$orderQueryString = '';
			if ($isSearch) {
				$orderQueryString = '&' . Sss_Ultility_CommonViewParamater::PAGE . '=' . $filterParam[Sss_Ultility_CommonViewParamater::PAGE] . '&s=1';
			} else {
				$orderQueryString = '&' . Sss_Ultility_CommonViewParamater::PAGE . '=' . $filterParam[Sss_Ultility_CommonViewParamater::PAGE];
			}

			//get company list
			$list       = $stockLocationTable->getAllStockLocationSearch($this->view->limit, 0, $filterParam);
			$queryString = '';
			if($instanceId != -1){
				$filterParam['instanceid'] = $instanceId;
				$list       = $stockLocationTable->getAllStockLocationSearchEdit($this->view->limit, 0, $filterParam);
				$queryString =  '&instanceid='.$instanceId;
			}
			$row        = $list->list;
			$pagination = $list->pagination;
			$this->view->assign(Sss_Ultility_CommonViewParamater::FILTER_PARAM, $filterParam);
			$this->view->assign(Sss_Ultility_CommonViewParamater::ROW, $row);
			$this->view->assign(Sss_Ultility_CommonViewParamater::PAGINATION, $pagination);
			$this->view->assign(Sss_Ultility_CommonViewParamater::QUERY_STRING, $queryString);
			$this->view->assign(Sss_Ultility_CommonViewParamater::ORDER_QUERY_STRING, $orderQueryString);
		}
	}
